//
//  CYDialPadVController.m
//  CreditAddressBook
//
//  Created by Lee on 15/4/22.
//  Copyright (c) 2015年 Lee. All rights reserved.
//

#import "CYDialPadVController.h"
#import "CYDialPadVController.h"
#import "CYTabBarVController.h"
#import "XCTabBarView.h"
#import "XCTabBarButton.h"
#import "CYCallRecordCVCell.h"
#import <CoreTelephony/CTCallCenter.h>
#import <CoreTelephony/CTCall.h>
#import "CYCollectionHeaderView.h"
#import "CYDialTool.h"
#import "CYCallHistory.h"
#import "RHAddressBook.h"
#import "CYABTool.h"
#import "CYCallRecord.h"
#import "CYABDetailVController.h"
#import "CYStatisticsView.h"
#import "CYStatisticsVC.h"
#import "CYCollectItem.h"
#import "CYCollectTool.h"
#import "CYCollectionVC.h"
#import "CYAddPersonTVC.h"
#import "CYDatabase.h"
#import "CYABDetailPageVC.h"
#import "CYCallCenter.h"
#import "CYJsonInfo.h"
#import "NSObject+MJKeyValue.h"
#import "CYTool.h"
#import "CYCallTableCell.h"


static CGFloat margin = -60;//collectionView的Margin
static NSString *const _ID = @"collectionCell";

@interface CYDialPadVController ()<CYTabBarVControllerDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout,UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, assign) BOOL isShow;//键盘是要显示还是隐藏
@property (nonatomic, assign) BOOL keyPadShowStatus;//键盘显示状态

@property (weak, nonatomic) IBOutlet UIView *keyPadView;
- (IBAction)btnClick:(id)sender;
@property (weak, nonatomic) IBOutlet UIView *numberView;
@property (weak, nonatomic) IBOutlet UILabel *numberLabel;//电话号码
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *keyPadNums;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *segmentBtns;
@property (weak, nonatomic) IBOutlet UIView *segmentBottomLine;

@property (nonatomic , assign) CGFloat segmentBottomLineX;//segmentBottomLine的X值，适配ios7

@property (nonatomic, strong) NSString *phoneNum;//电话号码
@property (nonatomic, strong) NSString *name;//姓名
@property (nonatomic, assign, getter = isNotificated) BOOL notification;//是否已发通知
@property (nonatomic, weak) XCTabBarView *tabBarView;
@property (nonatomic, assign, getter = isScrolled) BOOL scroll;//页面是否滚动过

@property (nonatomic, strong) NSString *callID;
@property (nonatomic, strong) NSArray *cyPersons;//CYPersons
@property (nonatomic, strong) NSArray *callLevel; //评分等级
@property (nonatomic, strong) NSArray *callHistory;//通话记录表
@property (nonatomic, strong) NSArray *callHistoryByNewlyCache;//最近通话记录
@property (nonatomic, strong) NSArray *callHistoryByTimesCache;//通话次数
@property (nonatomic, strong) NSArray *callHistoryByDurationCache;//通话时长
//@property (nonatomic, strong) NSArray *SCllHistoryBynotetion;//收藏纪录
@property (nonatomic, strong) CTCallCenter *callCenter;

@property (nonatomic, strong) UIButton *segSelectedBtn;//选中的导航按钮

@property (nonatomic, strong) CYCallRecord *sessionCallRecord;

@property (nonatomic, strong) NSMutableArray *searchResultPool;//检索结果存储池
@property (nonatomic, strong) NSString *searchKey;//检索字
@property (nonatomic, strong) NSArray *personCallRecords;//cyperson转cycallrecord

@property (nonatomic, strong) CYCollectionVC *collectionAB;//收藏controller

@property (nonatomic, strong) CYAddPersonTVC *addPersonV;//添加联系人view

@property (nonatomic , assign) CGFloat cellH;//cell的高度

@property (nonatomic, strong)UITableView *table;
@property (nonatomic, strong)NSMutableArray *callhistoryarray;

@end

@implementation CYDialPadVController

- (NSMutableArray *)searchResultPool {
    if (!_searchResultPool) {
        _searchResultPool = [NSMutableArray array];
    }
    return _searchResultPool;
}

//- (NSArray *)callHistory {
//    if (!_callHistory) {
//        _callHistory = self.callHistoryByNewly;
//    }
//    return _callHistory;
//}

/**
 *  收藏
 */
//- (NSArray *)SCllHistoryBynotetion {
//    
//    NSMutableArray *b = [NSMutableArray array];
//    if (!_SCllHistoryBynotetion) {
//        NSArray *a = [CYCollectTool sharedCollectTool].collectedDeals;
//        for (CYCollectItem *item in a) {
//            CYCallRecord *model = [[CYCallRecord alloc]init];
//            CYCallHistory *his = [[CYCallHistory alloc]init];
//            his.phone = item.phone;
//            his.name = item.name;
//            his.thumbnail =item.thumbnailLocal;
//            model.callHistory = his;
//            model.callHistory.headImageName = item.headImageName;
//            [b addObject:model];
//        }
//    }
//    return b;
//}

- (CYCollectionVC *)collectionAB {
    if (!_collectionAB) {
        _collectionAB = [[CYCollectionVC alloc] init];
        [self addChildViewController:_collectionAB];
        [_collectionAB didMoveToParentViewController:self];
        _collectionAB.view.frame = self.collectionView.frame;
    }
    return _collectionAB;
}

- (NSString *)name {
    if (!_name || [_name isEqualToString:@""]) {
        for (CYPerson *person in self.cyPersons) {
            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF == %@", self.phoneNum];
            NSString *phone = [[person.phones filteredArrayUsingPredicate:predicate] firstObject];
            if (phone) {
                _name = person.name;
                break;
            }
        }
    }
    return _name;
}

- (NSString *)phoneNum {
    return [self.numberLabel.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}

/**
 *  当号码显示面板改变时显示拨号与删除按钮
 *
 *  @return
 */
- (UILabel *)numberLabel {
    if (!self.isNotificated) {
        //发通知，显示拨号删除键
        [[NSNotificationCenter defaultCenter] postNotificationName:CYTabBarChangeNotification object:nil userInfo:@{CYEditTabBarShow: @YES}];
                    //通知已发
        self.notification = YES;
    }
    return _numberLabel;
}

- (CYAddPersonTVC *)addPersonV {
    if (!_addPersonV) {
        _addPersonV = [self.storyboard instantiateViewControllerWithIdentifier:@"CYAddPersonTVC"];
        [self addChildViewController:_addPersonV];
        [_addPersonV didMoveToParentViewController:self];
        _addPersonV.view.frame = self.collectionView.frame;
//        _addPersonV.view.backgroundColor = [UIColor clearColor];
    }
    return _addPersonV;
}

- (CGFloat)segmentBottomLineX {
    if (!_segmentBottomLineX) {
        _segmentBottomLineX = self.segmentBottomLine.x;
    }
    return _segmentBottomLineX;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    //基本参数设置
    [self setupParam];

    //键盘设置
    [self setupKeyPad];

    //设置collectionCell
    [self setupCollectionViewCell];

    //读取通讯录
    [self accessAllPeople];

    //加载通话记录
    [self callHistoryByNewlyWithIsReloadPeople:NO];
    
    //通讯录转cycallrecord
    [self callRecordFromCYPerson];

    //创键通讯录拨号监听
    [self setupNotification];
    
    //加载新的选择器
    //[self setupsegment];
}

- (void)setupsegment{
    UIView *segmentview = [[UIView alloc]initWithFrame:CGRectMake(0,64,self.view.width,50)];
    segmentview.backgroundColor = [UIColor blackColor];
    [self.view addSubview:segmentview];
    
//    UITableView *calltable = [[UITableView alloc]init];
//    calltable.frame = CGRectMake(0, segmentview.height+segmentview.y+2, self.view.width, 400);
    
    _table = [[UITableView alloc]initWithFrame:CGRectMake(0, segmentview.height+segmentview.y+2, self.view.width, 400) style:UITableViewStylePlain];
    _table.backgroundColor = [UIColor blueColor];
//    _table.dataSource = self;
    _table.delegate = self;
    _table.dataSource = self;
    [_table registerNib:[UINib nibWithNibName:@"CYCallTableCell" bundle:nil] forCellReuseIdentifier:@"CYCallTableCell"];
    [CYTool setExtraCellLineHiddenWithTableView:_table];
    [_table reloadData];
    [self.view addSubview:_table];
    
}

#pragma mark - tableview代理
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CYCallTableCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CYCallTableCell" forIndexPath:indexPath];
    //cell.model = _dataArray[indexPath.row];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    CYCallRecord *call = self.callHistory[indexPath.row];
    call.indexPath = indexPath;
    cell.callRecord = call;

    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120;
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.callHistory.count;
}
#pragma mark -
-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self= [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
    }
    return self;
}





- (void)setupParam {
    //设置导航按钮
    for (UIButton *btn in self.segmentBtns) {
        [btn setBackgroundImage:[UIImage imageWithColor:[UIColor groupTableViewBackgroundColor]] forState:UIControlStateSelected];
        
    }
    UIButton *btn = [self.segmentBtns firstObject];
    [self selectedBtn:btn];
}

- (void)setupCollectionViewCell {
    self.collectionView.contentInset = UIEdgeInsetsMake(margin, 16, 0, 16);
    
    //自定义点击事件隐藏键盘
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    //设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
    tapGestureRecognizer.cancelsTouchesInView = NO;
    //将触摸事件添加到当前view
    [self.collectionView addGestureRecognizer:tapGestureRecognizer];
    
    //隐藏滚动条
    self.collectionView.showsVerticalScrollIndicator = NO;
    
    [CYCallRecordCVCell collectionView:self.collectionView registerCellWithReuseIdentifier:_ID];
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    
    //列数
    int cols = 3;
    CGFloat width = CYScreeSize.width;
    //cell宽度
    CGFloat cellW = (width - 2 * 30)/cols;
    self.cellH = cellW + 20;
    // cell的大小
    layout.itemSize = CGSizeMake(cellW, self.cellH);
    self.collectionView.collectionViewLayout = layout;
    self.collectionView.alwaysBounceVertical = YES;
}

/**
 *  自定义点击事件隐藏键盘
 *
 *  @param tap
 */
-(void)keyboardHide:(UITapGestureRecognizer *)tap{
//    [self hiddenKeyPad:NO];
}

- (void)setupKeyPad {
    
    //监听底部导航，显示或隐藏键盘
    CYTabBarVController *tabBarVC = (CYTabBarVController *)self.tabBarController;
    tabBarVC.tabBarDelegate = self;
    
    self.keyPadShowStatus = YES;
    //设置键盘边框
    self.keyPadView.layer.borderWidth = 0.3;
    self.keyPadView.layer.shadowOffset = CGSizeMake(0, .2);
    self.keyPadView.layer.shadowOpacity = .8;
    for (UIButton *btn in self.keyPadNums) {
        btn.layer.borderWidth = 0.3;
        btn.layer.borderColor = [CYColor(180, 180, 180, 1) CGColor];
        btn.imageEdgeInsets = UIEdgeInsetsMake(12, 0, 12, 0);
        btn.imageView.contentMode = UIViewContentModeScaleAspectFit;
        
        [btn setBackgroundImage:[UIImage imageWithColor:[UIColor grayColor]] forState:UIControlStateHighlighted];
    }
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    if (!IOS8) {
        [self hiddenKeyPad:YES];
        self.isShow = YES;
    }
}

#pragma mark --- tabBar点击,删除，通话
- (void)tabBar:(XCTabBarView *)tab didSelectTo:(NSInteger)to {
    self.tabBarView = tab;
    //隐藏显示键盘
    if (to == CYTabBarItemTagA) {
        [self hiddenKeyPad:self.isShow];
    }else {
        //若点击的是第一个键以外的键，统统设置隐藏为是
        self.isShow = YES;
    }
}

/**
 *  tabBar代理方法，监听通话，删除按钮
 *
 *  @param controller
 *  @param sender
 */
- (void)tabBarController:(CYTabBarVController *)controller tabBarClicked:(UIButton *)sender {
    //拨号
    if ([sender.titleLabel.text isEqualToString:CYTabBarTitleD]) {
        
        __weak typeof(self) selfVC = self;
        //拨打电话
        [[CYCallCenter sharedCallCenter] callWithNumber:self.phoneNum name:self.name person:self.sessionCallRecord.person success:^{
            //更新通话记录
            [selfVC uploadCallHistory];
        } failure:^{
            CYLog(@"通话失败");
        }];
        //拨打电话时隐藏电话号码展示view
        [self hiddenSearchView];

    }else if ([sender.titleLabel.text isEqualToString:CYTabBarTitleE]) {//删除按钮
        //检索操作
        [self retrieval:nil];
        //显示键盘
        [self hiddenKeyPad:YES];
        if (self.numberLabel.text.length > 2) {
            self.numberLabel.text = [self.numberLabel.text substringToIndex:self.numberLabel.text.length - 1];
        }else {
            self.numberLabel.text = @" ";
            
            self.sessionCallRecord = nil;
            //发通知隐藏删除与通话键
            [[NSNotificationCenter defaultCenter] postNotificationName:CYTabBarChangeNotification object:nil userInfo:@{CYEditTabBarShow: @NO}];
            //通知已发
            self.notification = NO;
            
            self.numberView.hidden = YES;
            [self showAddPersonView];
        }
        
    }
}

/**
 *  长按事件
 */
- (void)tabBarController:(CYTabBarVController *)controller clickStatus:(NSInteger)status {
    CYLog(@"删除长按");
    self.numberLabel.text = @" ";
    self.sessionCallRecord = nil;
    //发通知隐藏删除与通话键
    [[NSNotificationCenter defaultCenter] postNotificationName:CYTabBarChangeNotification object:nil userInfo:@{CYEditTabBarShow: @NO}];
    //通知已发
    self.notification = NO;
    
    // 检索修改
    [self.searchResultPool removeAllObjects];
//    self.callHistory = self.callHistoryByNewly;
    [self callHistoryByNewlyWithIsReloadPeople:NO];
    self.searchKey = @"";
//    [self.collectionView reloadData];
    
    self.numberView.hidden = YES;
    //选中第一个导航按钮
    [self selectedBtn:[self.segmentBtns firstObject]];
    
    [self showAddPersonView];
}

/**
 *  拨打电话时隐藏电话号码展示view
 */
- (void)hiddenSearchView {
    //清空号码显示view及缓存
    [self numberViewClean];
    
    self.sessionCallRecord = nil;
    //发通知隐藏删除与通话键
    [[NSNotificationCenter defaultCenter] postNotificationName:CYTabBarChangeNotification object:nil userInfo:@{CYEditTabBarShow: @NO}];
    //通知已发
    self.notification = NO;
    
    // 检索修改
    [self.searchResultPool removeAllObjects];
    //    self.callHistory = self.callHistoryByNewly;
    [self callHistoryByNewlyWithIsReloadPeople:NO];
    self.searchKey = @"";
    //    [self.collectionView reloadData];
    
    //选中第一个导航按钮
    [self selectedBtn:[self.segmentBtns firstObject]];
    //显示或隐藏添加联系人view
    [self showAddPersonView];
}

#pragma mark - 键盘
/**
 *  隐藏或显示键盘
 *
 *  @param isShow
 */
- (void)hiddenKeyPad:(BOOL)isShow {
    self.isShow = isShow;
    [UIView animateWithDuration:0.3 animations:^{
        CGFloat heigt = self.keyPadView.frame.size.height;
        if (self.isShow) {//显示
            self.keyPadView.transform = CGAffineTransformIdentity;
            self.keyPadView.alpha = 1.0;
            
            //设置底部导航栏图标
            XCTabBarButton *btn = self.tabBarView.subviews[0];
            [btn setImage:[UIImage imageNamed:@"ic_dial_keybord_down"] forState:UIControlStateSelected];
            
            self.keyPadShowStatus = YES;
        }else {//隐藏
            self.keyPadView.transform = CGAffineTransformMakeTranslation(0, heigt);
            self.keyPadView.alpha = 0.0;
            
            //设置底部导航栏图标
            XCTabBarButton *btn = self.tabBarView.subviews[0];
            [btn setImage:[UIImage imageNamed:@"ic_dial_keybord_up"] forState:UIControlStateSelected];
            
            self.keyPadShowStatus = NO;
        }
        self.isShow = self.isShow? NO: YES;
    }];
}

/**
 *  键盘点击
 *
 *  @param sender
 */
- (void)btnClick:(id)sender {
    self.numberView.hidden = NO;
    UIButton *btn = sender;
    self.name = nil;//清除名字缓存
    self.sessionCallRecord = nil;
//    [self.number appendString:btn.titleLabel.text];
    if (self.numberLabel.text && self.numberLabel.text.length > 0 &&btn.titleLabel.text && !btn.titleLabel.text.isEmpty) {
        self.numberLabel.text = [self.numberLabel.text stringByAppendingString:btn.titleLabel.text];
        //通讯录，通话记录检索
        [self retrieval:btn.titleLabel.text];
    }
}

#pragma mark - 通讯录，通话记录检索
/**
 *  通话记录，通讯录检索
 *  num==nil 表示删除操作
 */
- (void)retrieval:(NSString *)num {
    
    if (num) {//键盘点击
        num = [num stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
        if (!self.searchKey) {
            self.searchKey = @"";
        }
        self.searchKey = [self.searchKey stringByAppendingString:num];
        
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"person.pinyinIndex contains %@ or person.phone contains %@ or callName contains %@ or person.pinyinHeaderIndex contains %@", self.searchKey, self.searchKey, self.searchKey, self.searchKey];
        
//        if (!self.callHistory.count) {
//            self.callHistory = self.callHistoryByNewly;
//        }
        NSMutableArray *filtered = [NSMutableArray array];
        //通话记录检索
        NSArray *callHistoryFiltered = [self.callHistoryByNewlyCache filteredArrayUsingPredicate:predicate];
        [filtered addObjectsFromArray:callHistoryFiltered];
        //通讯录检索
        NSArray *personFiltered = [self.personCallRecords filteredArrayUsingPredicate:predicate];
        [filtered addObjectsFromArray:personFiltered];
        self.callHistory = filtered;
        //缓存检索结果数组
        [self.searchResultPool addObject:self.callHistory];
        
        //显示添加联系人View
        [self showAddPersonView];
    } else {//键盘回删
        if (self.searchResultPool.count > 1) {
            //检索号码回删操作
            self.searchKey = [self.searchKey substringToIndex:self.searchKey.length - 1];
            [self.searchResultPool removeLastObject];
            self.callHistory = self.searchResultPool.lastObject;
            
            //显示添加联系人View
            [self showAddPersonView];
        } else {
            //清空检索缓存
            self.searchKey = @"";
            self.callHistory = self.callHistoryByNewlyCache;
            [self.searchResultPool removeAllObjects];
        }
    }
    //选中第一个导航按钮
    [self selectedBtn:[self.segmentBtns firstObject]];
    
    [self.collectionView reloadData];
}

/**
 *  清空号码显示view及缓存
 */
- (void)numberViewClean {
    self.numberView.hidden = YES;
    _numberLabel.text = @" ";
    [self.searchResultPool removeAllObjects];
    self.searchKey = @"";
}

/**
 *  通讯录-》CYCallRecord，用于检索
 */
- (void)callRecordFromCYPerson {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSMutableArray *arr = [NSMutableArray array];
        for (CYPerson *person in self.cyPersons) {
            CYCallRecord *call = [CYCallRecord callRecord];
            call.showTimeView = NO;
            call.showTimesImageView = NO;
            call.newlyCallDate = @"";
            call.dataType = CYCallRecordTypeABData;
            
            call.person = person;
            [arr addObject:call];
        }
        self.personCallRecords = arr;
    });
}

/**
 *  显示或隐藏添加联系人view
 */
- (void)showAddPersonView {
    BOOL isContain = [[self.view subviews] containsObject:self.addPersonV.view];
    if ((!self.callHistory || !self.callHistory.count) && self.searchKey.length) {
        self.addPersonV.phone = self.searchKey;
        if (!isContain) {
            [self.view insertSubview:self.addPersonV.view belowSubview:self.keyPadView];
        }
    } else if (isContain) {
        [self.addPersonV.view removeFromSuperview];
    }
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.callHistory.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    CYCallRecordCVCell *cell = [CYCallRecordCVCell collectionView:collectionView dequeueReusableCellWithReuseIdentifier:_ID forIndexPath:indexPath];
    
    CYCallRecord *call = self.callHistory[indexPath.row];
    switch (self.segSelectedBtn.tag) {
        case 1001:
            call.showTimesImageView = NO;
            call.showTimeView = YES;
            break;
            
        case 1002:
            call.showTimesImageView = YES;
            call.showTimeView = NO;
            break;
            
        case 1003:
            call.showTimeView = YES;
            call.showTimesImageView = NO;
            call.newlyCallDate = @"";
            break;
            
        case 1004:
            call.showTimesImageView = NO;
            call.showTimeView = NO ;
            break;
            
        default:
            call.showTimeView = NO;
            call.showTimesImageView = NO;
            break;
    }
    
    call.indexPath = indexPath;
    cell.cellH = self.cellH;
    cell.callRecord = call;
    [cell detailBtnAddTarget:self action:@selector(detailClick:)];
    
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath;{
    return CGSizeMake(self.view.width, 65);
    
}

/**
 *  cell头部detail按钮点击事件
 *
 *  @param sender UIButton
 */
- (void)detailClick:(id)sender {
    UIButton *btn = sender;
    CYCallRecord *call = self.callHistory[btn.tag];
//    CYABDetailVController *detail = [[CYABDetailVController alloc] init];
    CYPerson *person = call.person;//[self cypersonWithPhone:call.phone]
    if (!person) {
        person = [[CYPerson alloc] init];
        //自定义一个RHPerson
        RHAddressBook *ab = [CYABTool addressBook];
        RHPerson *rhperson = [ab newPersonInDefaultSource];
        rhperson.firstName = call.callHistory.phone;
        RHMutableMultiStringValue *rhms = [[RHMutableMultiStringValue alloc] initWithType:kABMultiStringPropertyType];
        [rhms addValue:call.callHistory.phone withLabel:RHPersonPhoneIPhoneLabel];
        rhperson.phoneNumbers = rhms;
        person.person = rhperson;
        person.add = YES;
    }
    person.pushTag = 1;
    person.segmentTag = 4;
//    detail.person = person;
//    detail.callRecord = call;
    CYABDetailPageVC *detail = [[CYABDetailPageVC alloc] initWithPerson:person andCallRecord:call defrId:nil];
    detail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detail animated:YES];
}

/**
 *  根据phone查找cyperson
 */
- (CYPerson *)cypersonWithPhone:(NSString *)phone {
    for (CYPerson *person in self.cyPersons) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF == %@", phone];
        NSString *phone = [[person.phones filteredArrayUsingPredicate:predicate] firstObject];
        if (phone) {
            return person;
        }
    }
    return nil;
}

#pragma mark - UICollectionViewDelegate cell点击
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    CYCallRecord *callRecord = self.callHistory[indexPath.row];
    if (callRecord.callHistory) {
        self.name = callRecord.callHistory.name;
        self.numberLabel.text = callRecord.callHistory.phone;
    } else if (callRecord.person) {
        self.name = callRecord.person.name;
        self.numberLabel.text = callRecord.person.phone;
    }
    self.sessionCallRecord = callRecord;
    
    __weak typeof(self) selfVC = self;
    //拨打电话
    [[CYCallCenter sharedCallCenter] callWithNumber:self.phoneNum name:self.name person:self.sessionCallRecord.person success:^{
        [selfVC uploadCallHistory];
        //清空号码显示view及缓存
        [self numberViewClean];
        //发通知隐藏删除与通话键
        [[NSNotificationCenter defaultCenter] postNotificationName:CYTabBarChangeNotification object:nil userInfo:@{CYEditTabBarShow: @NO}];
        //通知已发
        self.notification = NO;
    } failure:^{
        CYLog(@"通话失败");
    }];
    [self hiddenSearchView];
    //隐藏键盘
    [self hiddenKeyPad:NO];
    //显示号码view
//    self.numberView.hidden = NO;
}

#pragma mark - scrollView
//首次加载界面时会滚动触发该方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
//    CYLog(@"%f", scrollView.contentOffset.y);
    if (self.isScrolled && scrollView.contentOffset.y > -margin - 64) {
        if (self.keyPadShowStatus) {
            [self hiddenKeyPad:NO];
        }
    }
    self.scroll = YES;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self hiddenKeyPad:NO];
}

#pragma mark - 数据加载
/**
 *  读取通讯录数据
 */
- (void)accessAllPeople {
    if ([RHAddressBook authorizationStatus] != RHAuthorizationStatusAuthorized) return;
        
    self.cyPersons = [CYABTool cyPersonsFromRHPersons:[CYABTool accessAllPeople]];
}

/**
 *  刷新通讯录数据
 */
- (void)reloadAllPeople {
    if ([RHAddressBook authorizationStatus] != RHAuthorizationStatusAuthorized) return;
    self.cyPersons = [CYABTool cyPersonsFromRHPersons:[CYABTool reloadAllPeople]];
}

/**
 *  加载通话记录
 */
- (void)loadCallHistory:(NSDictionary *)params reloadPeople:(BOOL)isReload complete:(void (^)(NSArray *arr))complete {
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSArray *arr = [[CYDatabase sharedDatabase] callHistorysWithParam:params];
        if (isReload) {
            [self reloadAllPeople];
        }
//        #warning 该处应该改为采用ABRecordID精确查找RHPerson及其CYPerson, 注意陌生号码的处理
        for (CYCallRecord *callRecord in arr) {
            callRecord.person = [self cypersonWithPhone:callRecord.callHistory.phone];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            if (complete) {
                complete(arr);
            }
//            [self.collectionView reloadData];
        });
    });
}

#pragma mark - 从sqlite读取通话记录
/**
 *  最近通话
 */
- (void)callHistoryByNewlyWithIsReloadPeople:(BOOL)isReload {
    if (!self.callHistoryByNewlyCache) {
        [self loadCallHistory:nil reloadPeople:isReload complete:^(NSArray *arr) {
            self.callHistory = arr;
            self.callHistoryByNewlyCache = arr;
            [self.collectionView reloadData];
        }];
    } else {
        self.callHistory = self.callHistoryByNewlyCache;
        [self.collectionView reloadData];
    }
}

/**
 *  通话次数
 */
- (void)callHistoryByTimes {
    if (!self.callHistoryByTimesCache) {
        [self loadCallHistory:@{@"orderByCallNum": @YES} reloadPeople:NO complete:^(NSArray *arr) {
            self.callHistory = arr;
            self.callHistoryByTimesCache = arr;
            [self.collectionView reloadData];
        }];
    } else {
        self.callHistory = self.callHistoryByTimesCache;
        [self.collectionView reloadData];
    }
}

/**
 *  通话时长
 */
- (void)callHistoryByDuration {
    if (!self.callHistoryByDurationCache) {
        [self loadCallHistory:@{@"orderByCallDuration": @YES} reloadPeople:NO complete:^(NSArray *arr) {
            self.callHistory = arr;
            self.callHistoryByDurationCache = arr;
            [self.collectionView reloadData];
        }];
    } else {
        self.callHistory = self.callHistoryByDurationCache;
        [self.collectionView reloadData];
    }
}

#pragma mark - 监听操作
- (void)setupNotification {
    /**监听通讯录拨号 */
    [CYNotificationCenter addObserver:self selector:@selector(forTheCall:) name:CYCallStateDisconnectedKey object:nil];
    
    /**监听头像修改 */
    [CYNotificationCenter addObserver:self selector:@selector(imageChange:) name:CYAddressBookChangeNotification object:nil];
    
    //监听收藏拨号
    [CYNotificationCenter addObserver:self selector:@selector(dialFromCollection:) name:CYDialNotification object:nil];
    
    //监听陌生号码添加操作
    [CYNotificationCenter addObserver:self selector:@selector(reloadCallRecordData:) name:CYCallRecordChangeNotification object:nil];
    
    //监听陌生联系人添加操作
    [CYNotificationCenter addObserver:self selector:@selector(addNewPerson:) name:CYAddPersonNotification object:nil];
}

- (void)forTheCall:(NSNotification *)notifi {
    [self uploadCallHistory];
    //清空号码显示view及缓存
    [self numberViewClean];
}

- (void)imageChange:(NSNotification *)notifi {
    [self uploadCallHistory];
}

- (void)dialFromCollection:(NSNotification *)notifi {
    [self reloadData];
}

- (void)reloadCallRecordData:(NSNotification *)notifi {
    [self reloadData];
}

- (void)addNewPerson:(NSNotification *)notifi {
//    NSDictionary *userInfo = notifi.userInfo;
    //重新加载系统联系人
    [self reloadAllPeople];
    //重新生成CYCallRecord用于检索
    [self callRecordFromCYPerson];
    //清空号码显示view及缓存
    [self numberViewClean];
    //发通知隐藏删除与通话键
    [[NSNotificationCenter defaultCenter] postNotificationName:CYTabBarChangeNotification object:nil userInfo:@{CYEditTabBarShow: @NO}];
    //通知已发
    self.notification = NO;
    //显示添加联系人view
    [self showAddPersonView];
    
    [self reloadData];
}

/**更新通话记录显示*/
- (void)reloadData {
    self.callHistoryByNewlyCache = nil;
    [self callHistoryByNewlyWithIsReloadPeople:YES];
    self.callHistoryByTimesCache = nil;
    self.callHistoryByDurationCache = nil;
//    self.callHistory = nil;
    
//    [self.collectionView reloadData];
}

- (void) uploadCallHistory{
    [self reloadData];
    if (self.segSelectedBtn.tag != 1004) {
        //导航按钮选中第一个按钮
        [self selectedBtn:[self.segmentBtns firstObject]];
    }
}

#pragma mark -导航按钮点击事件
/**导航按钮点击事件*/
- (IBAction)segBtnClick:(id)sender {
    UIButton *btn = sender;
    if (self.segSelectedBtn == btn && btn.tag != 1005) return;
    //设置导航按钮为选中
    [self selectedBtn:btn];
    
    //隐藏键盘
    [self hiddenKeyPad:NO];
    
    //根据参数加载数据
    switch (btn.tag) {
        case 1002: {
            [self.collectionAB.view removeFromSuperview];
//            dispatch_async(dispatch_get_global_queue(0, 0), ^{
//                self.callHistory = self.callHistoryByTimes;
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [self.collectionView reloadData];
//                });
//            });
            self.callHistory = nil;
            [self callHistoryByTimes];
        }
            break;
            
        case 1003: {
            [self.collectionAB.view removeFromSuperview];
//            dispatch_async(dispatch_get_global_queue(0, 0), ^{
//                self.callHistory = self.callHistoryByDuration;
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [self.collectionView reloadData];
//                });
//            });
            self.callHistory = nil;
            [self callHistoryByDuration];
        }
            break;
            
        case 1004://收藏
//            self.callHistory = self.SCllHistoryBynotetion;
            [self.view addSubview:self.collectionAB.view];
            break;
            
        case 1005:
        {
            if ([[CYDatabase sharedDatabase] callHistorysWithParam:nil].count) {
                CYStatisticsVC *staticController = [[CYStatisticsVC alloc] init];
                staticController.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:staticController animated:YES];
            } else {
                CYAlertView(@"您还没有通话记录哦！");
            }
        }
            break;
            
        default: {
            [self.collectionAB.view removeFromSuperview];
//            dispatch_async(dispatch_get_global_queue(0, 0), ^{
//                self.callHistory = self.callHistoryByNewly;
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [self.collectionView reloadData];
//                });
//            });
            self.callHistory = nil;
            [self callHistoryByNewlyWithIsReloadPeople:NO];
        }
            break;
    }
}

- (void)reloadDataWithCallHistory:(NSArray *)arr {
    
}

/**选中导航按钮*/
- (void)selectedBtn:(UIButton *)btn {
    if (btn.tag == 1005) {
//        btn.backgroundColor = [UIColor grayColor];
//        [UIView animateWithDuration:1.f animations:^{
//            btn.backgroundColor = CYNaviThemeColor;
//        }];
    } else {
        int index = 0;
        if (self.segSelectedBtn) {
            index = btn.tag % 1000 - self.segSelectedBtn.tag % 1000;
        }
        //动画效果
        [UIView animateWithDuration:.5f delay:0 usingSpringWithDamping:.5 initialSpringVelocity:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
            //15为SB中减去的宽度
             //*** 不懂 ***
            self.segmentBottomLineX += index * (self.segmentBottomLine.width + 16);
            self.segmentBottomLine.x = self.segmentBottomLineX;
        } completion:nil];
        
//        self.segmentBottomLine.x += index * self.segmentBottomLine.width;
//        self.segSelectedBtn.backgroundColor = CYNaviThemeColor;
//        btn.backgroundColor = [UIColor grayColor];
        self.segSelectedBtn = btn;
    }
}

- (void)dealloc {
    [CYNotificationCenter removeObserver:self];
}

@end
